<template>
    <div class="background" :style="{ backgroundImage: `url(${bg5Url})`, minHeight: '100vh' }">
        <div class="search-row">
            <div class="search-wrapper">
                <input v-model="query" type="text" placeholder="请输入关键词" class="search-input" />
                <button @click="handleSearch" class="search-button">搜索</button>
            </div>
            <!-- 使用 visibility 控制显示，保持位置不变 -->
            <button :class="['cancel-button', { visible: isSearch }]" @click="cancelSearch">
                取消搜索
            </button>
        </div>

        <div class="filter-info">
            <div class="filters">
                <!-- 分类筛选 -->
                <div class="filter-group">
                    <label>分类筛选：</label>
                    <select v-model="filters.category">
                        <option value="null">全部</option>
                        <option value="document">文档</option>
                        <option value="video">视频</option>
                        <option value="voice">音频</option>
                        <option value="software">软件</option>
                        <option value="design">设计</option>
                        <option value="code">编程</option>
                        <option value="mod">工具</option>
                    </select>
                </div>

                <!-- 时间筛选 -->
                <div class="filter-group">
                    <label>时间筛选：</label>
                    <select v-model="filters.time">
                        <option value="null">不限</option>
                        <option value="week">最近一周</option>
                        <option value="month">最近一个月</option>
                        <option value="year">最近一年</option>
                    </select>
                </div>

                <!-- 排序方式 -->
                <div class="filter-group">
                    <label>排序方式：</label>
                    <select v-model="filters.sort">
                        <option value="null">综合排序</option>
                        <option value="latest">最新发布</option>
                        <option value="downloads">下载最多</option>
                        <option value="rating">评分最高</option>
                    </select>
                </div>
            </div>
        </div>

        <div class="result-grid">
            <!-- 循环展示模拟数据 -->
            <div class="result-card" v-for="(item, index) in result.results" :key="index" @click="goToDetail(item.id)"
                style="cursor: pointer">
                <div class="card-content">
                    <img :src="toolsIcon" alt="资源图" class="result-image" />
                    <div class="card-text">
                        <h3>{{ item.title }}</h3>
                        <p>类型：{{ item.type }}</p>
                    </div>
                </div>
            </div>
        </div>
        <div class="pagination">
            <p>
                <button @click="prevPage" :disabled="result.pageIndex === 1">上一页</button>
                <button @click="nextPage" :disabled="result.pageIndex === result.totalPages">下一页</button>
                跳转到
                <input type="number" v-model.number="jumpPage" min="1" :max="result.totalPages" style="width: 60px;" />
                <button @click="goToPage">跳转</button>
                当前第 {{ result.pageIndex }} 页 / 共 {{ result.totalPages }} 页
            </p>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import toolsIcon from '@/assets/images/ic/ic_sw_tool.png'
import bg5Url from '@/assets/images/background/resource_bg2.png'
import { Filters, Resource, ResourcePage } from '@/model/ResourceModels'
import { useRouter } from 'vue-router'
import { loadResourcePageToBack } from '@/service/ResourceService'

const result = reactive<ResourcePage>({
    total: 0,
    pageIndex: 1,
    totalPages: 1,
    results: []
});

const router = useRouter()

function goToDetail(id: number) {
    router.push(`/detail/${id}`)
}

function prevPage() {
    if (result.pageIndex > 1) {
        result.pageIndex--;
        loadPage(result.pageIndex);
    }
}

function nextPage() {
    console.log('点击下一页:', result.pageIndex)
    if (result.pageIndex < result.totalPages) {
        result.pageIndex++;
        loadPage(result.pageIndex);
    }
}

const jumpPage = ref<number>(1);

function goToPage() {
    if (
        jumpPage.value >= 1 &&
        jumpPage.value <= result.totalPages &&
        jumpPage.value !== result.pageIndex
    ) {
        result.pageIndex = jumpPage.value;
        loadPage(result.pageIndex);
    }
}


const searchCache = ref<ResourcePage[]>([])
const normalCache = ref<ResourcePage[]>([])

const currentPageList = computed(() => {
    if (isSearch.value) {
        return searchCache.value
    } else {
        return normalCache.value
    }
})
const query = ref('')
const isSearch = ref(false)

const filters = reactive<Filters>({
    category: 'null',
    time: 'null',
    sort: 'null'
})

const handleSearch = () => {
    console.log('搜索关键词:', query.value)
    console.log('筛选条件:', filters)
    if (
        !query.value
        && filters.category === 'null'
        && filters.time === 'null'
        && filters.sort === 'null'
    ) {
        isSearch.value = false
        result.pageIndex = 1
        loadPage(result.pageIndex)
    } else {
        isSearch.value = true
        searchCache.value = []
        result.pageIndex = 1
        loadPage(result.pageIndex)
    }

}

const cancelSearch = () => {
    console.log('取消搜索')
    isSearch.value = false
    searchCache.value = []
    result.pageIndex = 1
    loadPage(result.pageIndex)
}

// 模拟加载分页数据
function loadPage(pagepageIndex: number) {
    console.log(`加载第 ${pagepageIndex} 页的数据...此刻search:${isSearch.value}`)
    //到顶端
    window.scrollTo({ top: 0, behavior: 'smooth' })
    // 如果缓存中有，直接使用
    if (currentPageList.value[pagepageIndex - 1]) {
        const cached = currentPageList.value[pagepageIndex - 1]
        result.total = cached.total
        result.pageIndex = cached.pageIndex
        result.totalPages = cached.totalPages
        result.results = cached.results
        console.log(`从缓存里加载第 ${pagepageIndex} 页的数据...`)
        return
    }
    // 模拟接口返回 ResourcePage
    loadResourcePageToBack(query.value, filters, pagepageIndex, isSearch.value)
        .then(simulated => {
            if (simulated) {
                // 存入缓存
                normalCache.value[pagepageIndex - 1] = simulated
                // 更新当前页结果
                result.total = simulated.total
                result.pageIndex = simulated.pageIndex
                result.totalPages = simulated.totalPages
                result.results = simulated.results
                console.log(`从接口里加载第 ${pagepageIndex} 页的数据...`)
            }
        })
}

onMounted(() => {
    loadPage(result.pageIndex)
})
</script>

<style scoped>
.container {
    padding: 16px;
}

.search-row {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 12px;
  margin-top: 60px;
}

/* ✅ 搜索框变长（设置宽度） */
.search-wrapper {
  display: flex;
  align-items: center;
  background: #ffffffcc;
  border-radius: 32px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  width: 500px; /* 你可以根据页面需要设置更长，例如 600px、640px */
}

/* ✅ 保持输入框弹性填满 */
.search-input {
  flex: 1;
  padding: 12px 20px;
  border: none;
  outline: none;
  font-size: 16px;
  border-radius: 32px 0 0 32px;
  background: transparent;
}

/* 搜索按钮样式 */
.search-button {
  padding: 12px 20px;
  font-size: 16px;
  border: none;
  cursor: pointer;
  border-radius: 0 32px 32px 0;
  background-color: #409eff;
  color: #fff;
  transition: background-color 0.3s;
}

.search-button:hover {
  background-color: #66b1ff;
}

/* ✅ 取消按钮占位固定，但只在 isSearch 时显示 */
.cancel-button {
  padding: 12px 20px;
  font-size: 16px;
  border: none;
  cursor: pointer;
  background-color: #f56c6c;
  color: white;
  border-radius: 32px;
  transition: background-color 0.3s;
  visibility: hidden; /* 默认隐藏，占位置 */
  opacity: 0;
}

.cancel-button.visible {
  visibility: visible;
  opacity: 1;
}

.cancel-button:hover {
  background-color: #f78989;
}



.filter-info {
    max-width: 100%;
    margin: 20px auto 40px;
    font-size: 14px;
    color: #333;
    user-select: none;
}

.filters {
    margin-top: 8px;
    display: flex;
    flex-wrap: wrap;
    gap: 20px 40px;
    /* 横向40px，纵向20px间距 */
    justify-content: space-around;
}

.filter-group {
    display: flex;
    align-items: center;
    gap: 8px;
    min-width: 180px;
}

.filter-group label {
    font-weight: 600;
    color: #555;
    white-space: nowrap;
}

.filter-group select {
    padding: 4px 8px;
    border-radius: 6px;
    border: 1px solid #ccc;
    font-size: 14px;
    cursor: pointer;
    min-width: 100px;
}

.tag-cloud {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
}

.tag-cloud button {
    background: #eee;
    border: none;
    border-radius: 14px;
    padding: 4px 12px;
    font-size: 13px;
    cursor: pointer;
    color: #666;
    transition: all 0.3s ease;
}

.tag-cloud button.active {
    background: #409eff;
    color: #fff;
    box-shadow: 0 2px 8px rgb(64 158 255 / 0.4);
}

.tag-cloud button:hover {
    background: #cce4ff;
    color: #409eff;
}

.result-grid {
    display: grid;
    grid-template-columns: repeat(5, 1fr);
    /* 一行5列 */
    gap: 20px;
    /* 卡片间距 */
    max-width: 1200px;
    /* 最大宽度 */
    margin: 0 auto;
    padding: 30px 20px;
}

.result-card {
    background: rgba(255, 255, 255, 0.3);
    backdrop-filter: blur(10px);
    -webkit-backdrop-filter: blur(10px);
    border-radius: 15px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    overflow: hidden;
    transition: transform 0.3s ease;
    display: flex;
    flex-direction: column;
    /* 垂直排列 */
    height: 100%;
    /* 确保卡片高度一致 */
}

.result-card:hover {
    transform: translateY(-5px);
}

.result-image {
    width: 100%;
    aspect-ratio: 1/1;
    /* 正方形图片 */
    object-fit: cover;
    border-radius: 12px 12px 0 0;
    /* 只上圆角 */
}

.card-content {
    display: flex;
    flex-direction: column;
    /* 垂直排列内容 */
    flex: 1;
    /* 填充剩余空间 */
}

.card-text {
    padding: 15px;
    text-align: center;
}

.card-text h3,
.card-text p {
    margin: 5px 0;
    font-size: 16px;
}

.rating {
    display: inline-block;
    background-color: #eee;
    padding: 2px 8px;
    border-radius: 8px;
    margin-right: 6px;
    font-size: 14px;
}

.pagination {
    text-align: center;
    margin-top: 40px;
    padding-bottom: 30px;
}

.pagination button,
.pagination input {
    margin: 0 6px;
}

/* 响应式调整 - 小屏幕显示2列 */
@media (max-width: 768px) {
    .result-grid {
        grid-template-columns: repeat(4, 1fr);
    }
}

/* 超小屏幕显示1列 */
@media (max-width: 480px) {
    .result-grid {
        grid-template-columns: repeat(2, 1fr);
    }

    .result-card {
        width: 100%;
    }
}
</style>